<template>
  <div class="order-append-table">
    <div class="table">
      <a-table 
        :columns="columns" 
        :data-source="data" 
        bordered 
        size="small"
        :pagination="false"
        :scroll="{ x: 1400 , y: 580}">
        <template
          slot="operation"
          slot-scope="text, record, index"
        >
          <div>
            <a-button type="link" style="padding: 0;" @click="removeOrder(index)">
              <a-icon type="close" />
            </a-button>
          </div>
        </template>

        <template
          v-for="col in ['po', 'goodsNumber', 'quality', 'size', 'price', 'quantity', 'remark']"
          :slot="col"
          slot-scope="text, record, index"
        >
          <div :key="col">
            <a-input
              style="margin: -5px 0"
              :value="text"
              :data-index="index"
              v-if="!locked"
              @blur="e => handleChange(e.target.value, record.key, col)"
            />
            <span 
              v-else
              :data-index="index"
            >
            {{text}}
            </span>
          </div>
        </template>

        <template
          slot="goodsType"
          slot-scope="text, record"
        >
          <div>
            <goods-type-select v-if="!locked" @change="handleChange($event, record.key, 'goodsType')" :initial-value="text" @focus="this.dropdownVisibleChange()"></goods-type-select>
            <span 
              v-else
            >
            {{text}}
            </span>
          </div>
        </template>


        <template
          slot="size"
          slot-scope="text, record, index"
        >
          <div>
            <div v-if="!locked"  class="size-input">
              <a-input
                class="length"
                style="margin: -5px 0"
                :value="text[0]"
                :data-index="index"
                @blur="e => handleChange(e.target.value, record.key, 'sizeLength')"
              />
              <span>×</span>
              <a-input
                class="width"            
                style="margin: -5px 0"
                :value="text[1]"
                :data-index="index"
                @blur="e => handleChange(e.target.value, record.key, 'sizeWidth')"
              />
              <span>×</span>
              <a-input
                class="height"
                style="margin: -5px 0"
                :value="text[2]"
                :data-index="index"
                @blur="e => handleChange(e.target.value, record.key, 'sizeHeight')"
              />
              <span>mm</span>
            </div>
            <span 
              v-else
              :data-index="index"
            >
            {{sizeSpan(text)}}
            </span>
          </div>
        </template>


      </a-table>
    </div>
    <div class="operations">
      <a-button @click="appendRow">
        增加一行
      </a-button>
      <div class="confirm-operations">
        <a-button type="primary" v-if="!locked" @click="lock">
          锁定
        </a-button>
        <a-button type="primary" v-else @click="unlock">
          解除锁定
        </a-button>
        <confirm-modal @confirm="appendConfirm" :ans="ans" :disabled="!locked"></confirm-modal>
        <a-popconfirm
          title="确认取消新增订单？"
          ok-text="取消新增"
          cancel-text="继续"
          @confirm="handleCancel"
        >
          <a-button>
            取消
          </a-button>
        </a-popconfirm>
        <a-popconfirm
          title="确认清空所有行？"
          ok-text="确认清空"
          cancel-text="继续"
          @confirm="handleClear"
        >
          <a-button>
            清空
          </a-button>
        </a-popconfirm>
      </div>
    </div>
  </div>
</template>

<script>
import ConfirmModal from '@/components/modal/OrderAppendConfirmModal';
import GoodsTypeSelect from '@/components/select/GoodsTypeSelect';
import {
  fixedOneFloat,
  fixed3Float,
  fixedInt,
  times3IntFixed,
  times3FixedFloatInt
} from '@/utils/NumberChange.js';
import {
  orderAppendColumns
} from './init/tableInit.js';

import {
  orderAppendReq
} from '@/requests/orderRequests';

export default {
  name: "OrderAppendTable",
  data() {
    return {
      data: [],
      columns: orderAppendColumns,
      locked: false,
      ans: [],
    };
  },
  computed: {
    clientId() {
      return this.$route.params.clientId;
    }
  },
  methods: {
    /**
     * 点击确认，触发确认添加订单事件
    */
    appendConfirm(){
      // ans收集本table的数据
      const ans = this.ans;
      const clientId = this.clientId;
      const loaded = this.$message.loading('正在添加订单，请勿重复点击提交', 0);

      // 向后端提出 appendDelivery 请求
      orderAppendReq(clientId, ans).then((res) => {
        loaded();
        let orderIds = res.data;

        // 返回Order的主页
        this.$router.push({
          name: 'OrderIndex',
        });

        // 提示信息
        this.$notification['success']({
          message: '新增订单',
          description:
            `为${clientId}新增订单成功，新增订单${orderIds.length}条 `,
        });
        // 更新缓存
        this.$store.commit('updateOrdersCache');

        // 通知父组件，遗弃本Table。
        this.$emit('appendConfirm');
      }).catch((err) => {
        loaded();
        this.$notification['error']({
          message: '新增订单',
          description:
            `新增订单失败，失败信息 ${err.response.data.message}`,
        });
      });
    },
    // 输入框失去焦点时引发该事件
    /**
     * 输入框失去焦点时引发该事件
     * @param {string} value 输入框里的值
     * @param {string} key 行标记
     * @param {string} column 列名
     */
    handleChange(value, key, column) {
      // 复制数据
      const newData = [...this.data];

      // 获得失去焦点的输入框那一行
      const target = newData.filter(item => key === item.key)[0];

      // 数字
      const numberArray = ['price', 'quantity'];

      // size 列
      const sizeArray = ['sizeLength', 'sizeWidth', 'sizeHeight'];

      // 处理数字 —— 数量或者单价
      if (numberArray.indexOf(column) > -1) {

        // 数量转化成数字，如果转化不了，就返回0
        if (column == 'quantity' && value.trim().length > 0){
          value = fixedInt(value);
        }

        // 单价转化成二位浮点数，如果转化不了，就返回0
        else if (value.trim().length > 0) {
          value = fixed3Float(value);
        }

      }

      // 如果是 size
      if (sizeArray.indexOf(column) > -1) {
        const index = sizeArray.indexOf(column);

        // 转化成一位浮点数
        value = fixedOneFloat(value);

        // 如果是整数，转化成整数
        if (value.toString().indexOf('.0') > -1) {
          value = parseInt(value);
        }

        target['size'][index] = value;

        // 如果是后面的值，而前面的值还没有输入，那么前面的值默认为0
        const inValidArray = ['', undefined];
        if (index == 2 && value != '') {
          if (inValidArray.includes(target['size'][0])) {
            target['size'][0] = 0
          }
          if (inValidArray.includes(target['size'][1])) {
            target['size'][1] = 0
          }
        }

        if (index == 1 && value != '') {
          if (inValidArray.includes(target['size'][0])) {
            target['size'][0] = 0
          }
        }
      }
      else if (target) {
        target[column] = value;
      }

      this.data = newData;

      // 计算 amount
      if (numberArray.includes(column)) {
        
        // 数量和单价相乘得出金额
        // 但是如果数量和单价都是空的，那就不返回任何东西
        if (target['price'] == '' && target['quantity'] == '') {
          target['amount'] = ''
        }

        else {
          const amount = times3FixedFloatInt(target['price'], target['quantity']);
          target['amount'] = amount.toString() == "NaN" ? 0 : amount;
        }
      }
    },
    // 点击锁定，生成 ans
    lock() {
      this.locked = true;
      let ans = this.data.filter((value) => {
        // 是否不是全空，如果没有有效的数值，意味着
        let valid = false;
        const uselessArray = ['size', 'remark', 'amount', 'key', 'price'];
        for(let i in value) {
          // size、remark、amount、key、price 不计数，这意味着如果只有 size、remark、amount、key、price 是不行的。
          if (uselessArray.includes(i)) {
            continue;
          }
          // 只要有一个有效数据，就够了
          else {
            try {
              if (value[i].toString().trim().length > 0) {
                valid = true;
                break;
              }
            }
            catch(err) {
              
            }
          }
        }
        return valid;
      });

      this.ans = ans.map((value) => {
        // 克隆，防止原来的数组影响后面的
        const ansValue = Object.assign({}, value);
        // 全部转化成 以厘为单位 ，即 乘1000倍变成1000倍正整数。
        ansValue.price = times3IntFixed(value.price == "" ? 0 : value.price);
        ansValue.amount = times3IntFixed(value.amount == "" ? 0 : value.amount);
        ansValue.quantity = parseInt(value.quantity == ""? 0 : value.quantity);
        ansValue.size = this.sizeSpan(value.size);
        return ansValue;
      });
    },
    // 解锁
    unlock() {
      this.locked = false;
    },
    // 对 size 规整化
    sizeSpan(text) {
      if (text[2]) {
        return `${text[0]}x${text[1]}x${text[2]}`;
      }
      else if (text[1]) {
        return `${text[0]}x${text[1]}`;
      }
      else if (text[0]){
        return `${text[0]}`;
      }
      return '';
    },
    handleCancel() {
      this.$message.info('取消新增订单');
      this.$router.push({
        name: 'OrderIndex'
      });
    },
    handleClear() {
      this.$message.info('清空新增订单所有行');
      this.init();
    },
    init() {
      const data = [];
      for (let i = 0; i < 10; i++) {
        data.push({
          key: i.toString(),
          po: ``,
          goodsNumber: ``,
          goodsType: ``,
          quality: ``,
          size: new Array(3).fill(),
          quantity: '',
          price: '',
          amount: '',
          remark: ''
        });
      }
      this.data = data;
      this.locked = false;
      this.ans = [];
    },
    appendRow() {
      this.data.push({
        key: (parseInt(this.data[this.data.length - 1].key) + 10).toString(),
        po: ``,
        goodsNumber: ``,
        goodsType: ``,
        quality: ``,
        size: new Array(3).fill(),
        quantity: '',
        price: '',
        amount: '',
        remark: ''
      });
    },
    removeOrder(index) {
      this.data.splice(index, 1);

    }
  },
  components: {
    ConfirmModal,
    GoodsTypeSelect
  },
  mounted() {
    this.init();
  }
};
</script>

<style scoped lang="scss">
.order-append-table {

  >.table {
    .size-input {
      display: grid;
      grid-template-columns: 60px 10px 60px 10px 60px 35px;
      grid-column-gap: 2px;
      justify-content: center;
      justify-items: center;
    }

  }

  >.operations {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;

    >.confirm-operations {
      display: flex;
      >:not(:last-child) {
        margin-right: 20px;
      }
    }
  }
  
  overflow: auto;
  width: calc(100vw - 300px);
}
</style>

<style lang="scss">
.order-append-table {
  .table {
    th, td {
      text-align: center !important;
    }
    // 对scroller滑块的修饰
    * {
      &::-webkit-scrollbar {
        width: 8px;
        height: 8px;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 8px;
        background-color: hsla(225, 54%, 48%, 0.3);
        transition: background-color 0.3s;

        &:hover {
          background: #bbb;
        }
      }

      &::-webkit-scrollbar-track {
        background: #ededed;
      }
    }

    .ant-table-header {
      min-width: auto !important;
    }
  }
}


</style>
